<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel数据处理器 - 中医症状汤药数据库</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 40px;
        }

        .info-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 30px;
            border-left: 5px solid #4CAF50;
        }

        .info-card h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.3em;
        }

        .process-flow {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .process-step {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .process-step:hover {
            border-color: #4CAF50;
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }

        .process-step .step-number {
            background: #4CAF50;
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin: 0 auto 15px;
        }

        .controls {
            display: flex;
            gap: 20px;
            justify-content: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 15px 30px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
        }

        .btn-primary:hover {
            background: linear-gradient(45deg, #45a049, #3d8b40);
            transform: translateY(-2px);
            box-shadow: 0 8px 15px rgba(76, 175, 80, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .result-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-top: 30px;
            display: none;
        }

        .result-container.show {
            display: block;
        }

        .loading {
            text-align: center;
            padding: 40px;
            display: none;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4CAF50;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            border: 2px solid #e0e0e0;
        }

        .stat-value {
            font-size: 2em;
            font-weight: bold;
            color: #4CAF50;
        }

        .stat-label {
            color: #666;
            margin-top: 5px;
        }

        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .alert-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .alert-warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
        }

        pre {
            background: #f4f4f4;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            font-size: 12px;
        }

        .data-preview {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        .file-info {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            color: #1565c0;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }

            .header {
                padding: 20px;
            }

            .header h1 {
                font-size: 2em;
            }

            .content {
                padding: 20px;
            }

            .controls {
                flex-direction: column;
                align-items: center;
            }

            .btn {
                width: 100%;
                max-width: 300px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Excel数据处理器</h1>
            <p>多语言中医症状汤药数据库导入系统</p>
        </div>

        <div class="content">
            <div class="file-info">
                <strong>📁 数据文件位置：</strong> D:\phpstudy_pro\ai\intvale\ai_1\doc\sbb.xlsx<br>
                <strong>🔄 处理模式：</strong> 调试模式（不会实际插入数据库）
            </div>

            <div class="info-card">
                <h3>🎯 处理说明</h3>
                <p>本系统将Excel文件中的中医症状和汤药数据导入到多语言数据库中，支持中文、英文、日文、白俄罗斯文四种语言。处理过程包括数据清洗、编码修复、语义化分类匹配和多语言翻译。</p>
            </div>

            <div class="process-flow">
                <div class="process-step">
                    <div class="step-number">1</div>
                    <h4>分类处理</h4>
                    <p>处理D列分类数据，创建症状分类的多语言版本</p>
                </div>
                <div class="process-step">
                    <div class="step-number">2</div>
                    <h4>症状处理</h4>
                    <p>处理B列+C列症状数据，进行语义化分类匹配</p>
                </div>
                <div class="process-step">
                    <div class="step-number">3</div>
                    <h4>汤药处理</h4>
                    <p>处理A列汤药数据，关联对应的症状信息</p>
                </div>
            </div>

            <div class="controls">
                <button class="btn btn-primary" onclick="processExcelData()">
                    🚀 一键处理所有数据（真实入库）
                </button>
                <button class="btn btn-primary" onclick="insertCategoriesAndSymptoms()" style="background: #28a745;">
                    ✅ 插入分类和症状数据（真实）
                </button>
                <button class="btn btn-secondary" onclick="simpleProcessExcelData()" style="background: #6c757d;">
                    🔧 简化版处理
                </button>
                <button class="btn btn-secondary" onclick="getStats()">
                    📊 查看统计信息
                </button>
                <button class="btn btn-secondary" onclick="getDatabaseData()" style="background: #17a2b8;">
                    🗄️ 查看数据库数据
                </button>
                <button class="btn btn-secondary" onclick="checkDatabaseStatus()" style="background: #6f42c1;">
                    🔍 检查数据库状态
                </button>
                <button class="btn btn-secondary" onclick="debugExcelData()" style="background: #dc3545;">
                    🔍 调试Excel原始数据
                </button>
                <button class="btn btn-secondary" onclick="testSplitLogic()" style="background: #ffc107;">
                    🧪 测试分割逻辑
                </button>
            </div>

            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在处理数据，请稍候...</p>
            </div>

            <div class="result-container" id="result-container">
                <h3>处理结果</h3>
                <div id="result-content"></div>
            </div>
        </div>
    </div>

    <script>
        function showLoading() {
            document.getElementById('loading').classList.add('show');
            document.getElementById('result-container').classList.remove('show');
        }

        function hideLoading() {
            document.getElementById('loading').classList.remove('show');
        }

        function showResult(content) {
            document.getElementById('result-content').innerHTML = content;
            document.getElementById('result-container').classList.add('show');
        }

        function processExcelData() {
            if (!confirm('确定要将所有数据（分类、症状、汤药）插入数据库吗？\n\n注意：\n- 这会真正修改数据库\n- 已存在的数据会被跳过\n- 使用事务保证数据一致性')) {
                return;
            }

            showLoading();

            fetch('/index/excelprocessor/processExcelData', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">✅ ' + data.msg + '</div>';

                    if (data.data) {
                        // 显示汇总信息
                        if (data.data.summary) {
                            html += '<h4>📊 数据处理汇总：</h4>';
                            html += '<div class="stats-grid">';
                            html += '<div class="stat-card">';
                            html += '<div class="stat-label">分类数据</div>';
                            html += '<div style="font-size: 14px; margin-top: 10px;">';
                            html += '<div>新增: <strong style="color: #28a745;">' + data.data.summary.categories.new + '</strong></div>';
                            html += '<div>已存在: <strong style="color: #6c757d;">' + data.data.summary.categories.exists + '</strong></div>';
                            html += '<div>总计: <strong>' + data.data.summary.categories.total + '</strong></div>';
                            html += '</div></div>';

                            html += '<div class="stat-card">';
                            html += '<div class="stat-label">症状数据</div>';
                            html += '<div style="font-size: 14px; margin-top: 10px;">';
                            html += '<div>新增: <strong style="color: #28a745;">' + data.data.summary.symptoms.new + '</strong></div>';
                            html += '<div>已存在: <strong style="color: #6c757d;">' + data.data.summary.symptoms.exists + '</strong></div>';
                            html += '<div>总计: <strong>' + data.data.summary.symptoms.total + '</strong></div>';
                            html += '</div></div>';

                            html += '<div class="stat-card">';
                            html += '<div class="stat-label">汤药数据</div>';
                            html += '<div style="font-size: 14px; margin-top: 10px;">';
                            html += '<div>新增: <strong style="color: #28a745;">' + data.data.summary.formulas.new + '</strong></div>';
                            html += '<div>已存在: <strong style="color: #6c757d;">' + data.data.summary.formulas.exists + '</strong></div>';
                            html += '<div>总计: <strong>' + data.data.summary.formulas.total + '</strong></div>';
                            html += '</div></div>';

                            html += '<div class="stat-card"><div class="stat-value">' + data.data.data_count + '</div><div class="stat-label">Excel总行数</div></div>';
                            html += '</div>';
                        } else {
                            // 旧版本兼容
                            html += '<div class="stats-grid">';
                            html += '<div class="stat-card"><div class="stat-value">' + data.data.categories_processed + '</div><div class="stat-label">分类已处理</div></div>';
                            html += '<div class="stat-card"><div class="stat-value">' + data.data.symptoms_processed + '</div><div class="stat-label">症状已处理</div></div>';
                            html += '<div class="stat-card"><div class="stat-value">' + data.data.formulas_processed + '</div><div class="stat-label">汤药已处理</div></div>';
                            html += '<div class="stat-card"><div class="stat-value">' + data.data.data_count + '</div><div class="stat-label">总数据行数</div></div>';
                            html += '</div>';
                        }

                        if (data.data.errors && data.data.errors.length > 0) {
                            html += '<div class="alert alert-warning"><strong>⚠️ 处理警告：</strong><ul>';
                            data.data.errors.forEach(error => {
                                html += '<li>' + error + '</li>';
                            });
                            html += '</ul></div>';
                        }

                        // 显示处理后的完整数据数组
                        if (data.data.categories_data && data.data.categories_data.length > 0) {
                            html += '<h4>📋 处理后的分类数据数组（共 ' + data.data.categories_data.length + ' 条）：</h4>';
                            html += '<div class="data-preview">';
                            html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #f5f5f5; border-radius: 5px;">点击展开/收起完整分类数据数组</summary>';
                            html += '<pre style="background: #f8f9fa; padding: 15px; border-radius: 5px; font-size: 11px; line-height: 1.4; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data.data.categories_data, null, 2) + '</pre>';
                            html += '</details>';

                            // 显示前几条的可视化预览
                            html += '<h5>可视化预览（前5条）：</h5>';
                            data.data.categories_data.slice(0, 5).forEach((category, index) => {
                                const borderColor = category.status === 'exists' ? '#6c757d' : '#4CAF50';
                                const bgColor = category.status === 'exists' ? '#f8f9fa' : '#f9fff9';
                                const statusText = category.status === 'exists' ? '已存在' : '新增';
                                const statusColor = category.status === 'exists' ? '#6c757d' : '#28a745';

                                html += '<div style="border: 1px solid ' + borderColor + '; margin: 10px 0; padding: 15px; border-radius: 5px; background: ' + bgColor + ';">';
                                html += '<h6 style="color: ' + borderColor + '; margin-bottom: 10px;">分类 ' + (index + 1) + '：' + category.name_zh_cn + ' <span style="background: ' + statusColor + '; color: white; padding: 2px 8px; border-radius: 3px; font-size: 11px; margin-left: 10px;">' + statusText + '</span></h6>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; font-size: 12px;">';
                                html += '<div><strong>中文：</strong>' + category.name_zh_cn + '</div>';
                                html += '<div><strong>英文：</strong>' + (category.name_en_us || '待生成') + '</div>';
                                html += '<div><strong>日文：</strong>' + (category.name_ja_jp || '待生成') + '</div>';
                                html += '<div><strong>白俄文：</strong>' + (category.name_be_by || '待生成') + '</div>';
                                html += '</div>';
                                if (category.id) {
                                    html += '<div style="margin-top: 8px; font-size: 12px;"><strong>数据库ID：</strong>' + category.id + '</div>';
                                }
                                html += '<div style="margin-top: 8px; font-size: 12px;"><strong>操作：</strong>' + (category.action || '无') + '</div>';
                                html += '</div>';
                            });
                            html += '</div>';
                        }

                        if (data.data.symptoms_data && data.data.symptoms_data.length > 0) {
                            html += '<h4>🔍 处理后的症状数据数组（共 ' + data.data.symptoms_data.length + ' 条）：</h4>';
                            html += '<div class="data-preview">';
                            html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #f5f5f5; border-radius: 5px;">点击展开/收起完整症状数据数组</summary>';
                            html += '<pre style="background: #f8f9fa; padding: 15px; border-radius: 5px; font-size: 11px; line-height: 1.4; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data.data.symptoms_data, null, 2) + '</pre>';
                            html += '</details>';

                            // 显示前几条的可视化预览
                            html += '<h5>可视化预览（前3条）：</h5>';
                            data.data.symptoms_data.slice(0, 3).forEach((symptom, index) => {
                                html += '<div style="border: 1px solid #2196F3; margin: 10px 0; padding: 15px; border-radius: 5px; background: #f0f8ff;">';
                                html += '<h6 style="color: #2196F3; margin-bottom: 10px;">症状 ' + (index + 1) + '：' + symptom.name_zh_cn + '</h6>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; font-size: 12px;">';
                                html += '<div><strong>中文：</strong>' + symptom.name_zh_cn + '</div>';
                                html += '<div><strong>英文：</strong>' + symptom.name_en_us + '</div>';
                                html += '<div><strong>日文：</strong>' + symptom.name_ja_jp + '</div>';
                                html += '<div><strong>白俄文：</strong>' + symptom.name_be_by + '</div>';
                                html += '</div>';
                                html += '<div style="margin-top: 8px; font-size: 12px;">';
                                html += '<div><strong>分类ID：</strong>' + (symptom.category_id || '待匹配') + '</div>';
                                html += '<div><strong>描述：</strong>' + symptom.description_zh_cn + '</div>';
                                html += '</div>';
                                html += '</div>';
                            });
                            html += '</div>';
                        }

                        if (data.data.formulas_data && data.data.formulas_data.length > 0) {
                            html += '<h4>💊 处理后的汤药数据数组（共 ' + data.data.formulas_data.length + ' 条）：</h4>';
                            html += '<div class="data-preview">';
                            html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #f5f5f5; border-radius: 5px;">点击展开/收起完整汤药数据数组</summary>';
                            html += '<pre style="background: #f8f9fa; padding: 15px; border-radius: 5px; font-size: 11px; line-height: 1.4; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data.data.formulas_data, null, 2) + '</pre>';
                            html += '</details>';

                            // 显示前几条的可视化预览
                            html += '<h5>可视化预览（前3条）：</h5>';
                            data.data.formulas_data.slice(0, 3).forEach((formula, index) => {
                                html += '<div style="border: 1px solid #FF9800; margin: 10px 0; padding: 15px; border-radius: 5px; background: #fff8f0;">';
                                html += '<h6 style="color: #FF9800; margin-bottom: 10px;">汤药 ' + (index + 1) + '：' + formula.name_zh_cn + '</h6>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; font-size: 12px;">';
                                html += '<div><strong>中文：</strong>' + formula.name_zh_cn + '</div>';
                                html += '<div><strong>英文：</strong>' + formula.name_en_us + '</div>';
                                html += '<div><strong>日文：</strong>' + formula.name_ja_jp + '</div>';
                                html += '<div><strong>白俄文：</strong>' + formula.name_be_by + '</div>';
                                html += '</div>';
                                html += '<div style="margin-top: 8px; font-size: 12px;">';
                                html += '<div><strong>主证状ID：</strong>' + (formula.main_symptom_ids || '无') + '</div>';
                                html += '<div><strong>兼症状ID：</strong>' + (formula.side_symptom_ids || '无') + '</div>';
                                html += '<div><strong>描述：</strong>' + formula.description_zh_cn + '</div>';
                                html += '</div>';
                                html += '</div>';
                            });
                            html += '</div>';
                        }

                        // 显示完整的返回数据结构
                        html += '<h4>🔧 完整返回数据结构：</h4>';
                        html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #e9ecef; border-radius: 5px;">点击展开/收起完整JSON数据</summary>';
                        html += '<pre style="background: #f1f3f4; padding: 15px; border-radius: 5px; font-size: 10px; line-height: 1.3; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data, null, 2) + '</pre>';
                        html += '</details>';
                    }

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }

        function simpleProcessExcelData() {
            showLoading();

            fetch('/index/excelprocessor/simpleProcessExcelData', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">🔧 ' + data.msg + '</div>';

                    if (data.data) {
                        html += '<div class="stats-grid">';
                        html += '<div class="stat-card"><div class="stat-value">' + data.data.data_count + '</div><div class="stat-label">Excel总行数</div></div>';
                        html += '</div>';

                        // 显示原始Excel数据
                        if (data.data.raw_excel_data && data.data.raw_excel_data.length > 0) {
                            html += '<h4>📊 Excel原始数据：</h4>';
                            html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #f5f5f5; border-radius: 5px;">点击展开/收起Excel原始数据</summary>';
                            html += '<pre style="background: #f8f9fa; padding: 15px; border-radius: 5px; font-size: 11px; line-height: 1.4; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data.data.raw_excel_data, null, 2) + '</pre>';
                            html += '</details>';
                        }

                        // 显示处理结果
                        if (data.data.processed_data && data.data.processed_data.length > 0) {
                            html += '<h4>🔍 简化处理结果（每行数据详情）：</h4>';
                            html += '<div class="data-preview">';
                            data.data.processed_data.slice(0, 10).forEach((row, index) => {
                                html += '<div style="border: 1px solid #28a745; margin: 10px 0; padding: 15px; border-radius: 5px; background: #f8fff8;">';
                                html += '<h6 style="color: #28a745; margin-bottom: 10px;">第' + row.row_index + '行数据：</h6>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; font-size: 12px;">';
                                html += '<div><strong>A列(汤药):</strong> "' + (row.formula_name || '空') + '" (长度:' + row.formula_name_length + ')</div>';
                                html += '<div><strong>B列(主症状):</strong> "' + (row.main_symptoms || '空') + '" (长度:' + row.main_symptoms_length + ')</div>';
                                html += '<div><strong>C列(兼症状):</strong> "' + (row.side_symptoms || '空') + '" (长度:' + row.side_symptoms_length + ')</div>';
                                html += '<div><strong>D列(分类):</strong> "' + (row.categories || '空') + '" (长度:' + row.categories_length + ')</div>';
                                html += '</div>';
                                html += '</div>';
                            });
                            html += '</div>';

                            html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #f5f5f5; border-radius: 5px;">点击展开/收起所有处理数据</summary>';
                            html += '<pre style="background: #f8f9fa; padding: 15px; border-radius: 5px; font-size: 11px; line-height: 1.4; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data.data.processed_data, null, 2) + '</pre>';
                            html += '</details>';
                        }

                        // 显示完整JSON
                        html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #e9ecef; border-radius: 5px;">点击展开/收起完整JSON数据</summary>';
                        html += '<pre style="background: #f1f3f4; padding: 15px; border-radius: 5px; font-size: 10px; line-height: 1.3; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data, null, 2) + '</pre>';
                        html += '</details>';
                    }

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }

        function getStats() {
            showLoading();

            fetch('/index/excelprocessor/getStats', {
                method: 'GET',
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">📊 数据库统计信息</div>';
                    html += '<div class="stats-grid">';
                    html += '<div class="stat-card"><div class="stat-value">' + data.data.categories_count + '</div><div class="stat-label">症状分类总数</div></div>';
                    html += '<div class="stat-card"><div class="stat-value">' + data.data.symptoms_count + '</div><div class="stat-label">症状总数</div></div>';
                    html += '<div class="stat-card"><div class="stat-value">' + data.data.formulas_count + '</div><div class="stat-label">汤药总数</div></div>';
                    html += '</div>';

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }

        function getDatabaseData() {
            showLoading();

            fetch('/index/excelprocessor/getDatabaseData', {
                method: 'GET',
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">🗄️ ' + data.msg + '</div>';

                    if (data.data) {
                        if (data.data.categories_data && data.data.categories_data.length > 0) {
                            html += '<h4>📋 数据库中的分类数据（最新10条）：</h4>';
                            html += '<div class="data-preview">';
                            data.data.categories_data.forEach((category, index) => {
                                html += '<div style="border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px; background: #fff;">';
                                html += '<h5 style="color: #4CAF50; margin-bottom: 10px;">ID: ' + category.id + ' - ' + category.name_zh_cn + ' <small style="color: #999;">(' + category.created_at + ')</small></h5>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">';
                                html += '<div><strong>中文：</strong>' + category.name_zh_cn + '</div>';
                                html += '<div><strong>英文：</strong>' + category.name_en_us + '</div>';
                                html += '<div><strong>日文：</strong>' + category.name_ja_jp + '</div>';
                                html += '<div><strong>白俄文：</strong>' + category.name_be_by + '</div>';
                                html += '</div>';
                                html += '<div style="margin-top: 10px;"><strong>中文描述：</strong>' + category.description_zh_cn + '</div>';
                                html += '<div><strong>英文描述：</strong>' + category.description_en_us + '</div>';
                                html += '</div>';
                            });
                            html += '</div>';
                        }

                        if (data.data.symptoms_data && data.data.symptoms_data.length > 0) {
                            html += '<h4>🔍 数据库中的症状数据（最新15条）：</h4>';
                            html += '<div class="data-preview">';
                            data.data.symptoms_data.forEach((symptom, index) => {
                                html += '<div style="border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px; background: #fff;">';
                                html += '<h5 style="color: #2196F3; margin-bottom: 10px;">ID: ' + symptom.id + ' - ' + symptom.name_zh_cn + ' <small style="color: #999;">(' + symptom.created_at + ')</small></h5>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">';
                                html += '<div><strong>中文：</strong>' + symptom.name_zh_cn + '</div>';
                                html += '<div><strong>英文：</strong>' + symptom.name_en_us + '</div>';
                                html += '<div><strong>日文：</strong>' + symptom.name_ja_jp + '</div>';
                                html += '<div><strong>白俄文：</strong>' + symptom.name_be_by + '</div>';
                                html += '</div>';
                                html += '<div style="margin-top: 10px;">';
                                html += '<div><strong>分类：</strong>' + (symptom.category_name || '未分类') + ' (ID: ' + (symptom.category_id || 'null') + ')</div>';
                                html += '<div><strong>关键词：</strong>' + (symptom.keywords_zh_cn || '无') + '</div>';
                                html += '<div><strong>中文描述：</strong>' + symptom.description_zh_cn + '</div>';
                                html += '</div>';
                                html += '</div>';
                            });
                            html += '</div>';
                        }

                        if (data.data.formulas_data && data.data.formulas_data.length > 0) {
                            html += '<h4>💊 数据库中的汤药数据（最新10条）：</h4>';
                            html += '<div class="data-preview">';
                            data.data.formulas_data.forEach((formula, index) => {
                                html += '<div style="border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px; background: #fff;">';
                                html += '<h5 style="color: #FF9800; margin-bottom: 10px;">ID: ' + formula.id + ' - ' + formula.name_zh_cn + ' <small style="color: #999;">(' + formula.created_at + ')</small></h5>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">';
                                html += '<div><strong>中文：</strong>' + formula.name_zh_cn + '</div>';
                                html += '<div><strong>英文：</strong>' + formula.name_en_us + '</div>';
                                html += '<div><strong>日文：</strong>' + formula.name_ja_jp + '</div>';
                                html += '<div><strong>白俄文：</strong>' + formula.name_be_by + '</div>';
                                html += '</div>';
                                html += '<div style="margin-top: 10px;">';
                                html += '<div><strong>主证状ID列表：</strong>' + (formula.main_symptom_ids || '无') + '</div>';
                                html += '<div><strong>兼症状ID列表：</strong>' + (formula.side_symptom_ids || '无') + '</div>';
                                html += '<div><strong>主证状（关联）：</strong>' + (formula.main_symptom_names || '无') + '</div>';
                                html += '<div><strong>兼症状（关联）：</strong>' + (formula.side_symptom_names || '无') + '</div>';
                                html += '<div><strong>配方：</strong>' + formula.ingredients_zh_cn + '</div>';
                                html += '<div><strong>用法：</strong>' + formula.usage_method_zh_cn + '</div>';
                                html += '<div><strong>功效：</strong>' + formula.effects_zh_cn + '</div>';
                                html += '</div>';
                                html += '</div>';
                            });
                            html += '</div>';
                        }

                        if ((!data.data.categories_data || data.data.categories_data.length === 0) &&
                            (!data.data.symptoms_data || data.data.symptoms_data.length === 0) &&
                            (!data.data.formulas_data || data.data.formulas_data.length === 0)) {
                            html += '<div class="alert alert-warning">⚠️ 数据库中暂无数据，请先处理Excel数据。</div>';
                        }
                    }

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }

        function debugExcelData() {
            showLoading();

            fetch('/index/excelprocessor/debugExcelData', {
                method: 'GET',
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">🔍 ' + data.msg + '</div>';
                    html += '<div><strong>文件路径：</strong>' + data.data.file_path + '</div>';
                    html += '<div><strong>总行数：</strong>' + data.data.total_rows + '</div>';

                    html += '<h4>📊 Excel原始数据（前10行）：</h4>';
                    html += '<div class="data-preview">';

                    Object.keys(data.data.raw_data).forEach(rowKey => {
                        const row = data.data.raw_data[rowKey];
                        html += '<div style="border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px; background: #fff;">';
                        html += '<h5 style="color: #dc3545; margin-bottom: 15px;">' + rowKey + '</h5>';

                        ['A', 'B', 'C', 'D'].forEach(col => {
                            if (row[col]) {
                                html += '<div style="border: 1px solid #eee; margin: 5px 0; padding: 10px; border-radius: 3px; background: #f9f9f9;">';
                                html += '<h6 style="color: #666; margin-bottom: 8px;">列 ' + col + ':</h6>';
                                html += '<div style="font-size: 12px; line-height: 1.4;">';
                                html += '<div><strong>原始值:</strong> ' + JSON.stringify(row[col].raw) + '</div>';
                                html += '<div><strong>计算值:</strong> ' + JSON.stringify(row[col].calculated) + '</div>';
                                html += '<div><strong>格式化值:</strong> ' + JSON.stringify(row[col].formatted) + '</div>';
                                html += '<div><strong>数据类型:</strong> ' + row[col].raw_type + '</div>';
                                html += '<div><strong>编码检测:</strong> ' + (row[col].mb_detect || 'unknown') + '</div>';
                                html += '<div><strong>字符长度:</strong> ' + row[col].strlen + ' / UTF-8长度: ' + row[col].mb_strlen + '</div>';
                                html += '</div>';
                                html += '</div>';
                            }
                        });

                        html += '</div>';
                    });

                    html += '</div>';
                    html += '<details style="margin: 10px 0;"><summary style="cursor: pointer; font-weight: bold; padding: 10px; background: #e9ecef; border-radius: 5px;">点击展开/收起完整JSON数据</summary>';
                    html += '<pre style="background: #f1f3f4; padding: 15px; border-radius: 5px; font-size: 10px; line-height: 1.3; overflow-x: auto; margin: 10px 0;">' + JSON.stringify(data, null, 2) + '</pre>';
                    html += '</details>';

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }

        function insertCategoriesAndSymptoms() {
            if (!confirm('确定要将分类和症状数据插入数据库吗？\n\n注意：\n- 这会真正修改数据库\n- 已存在的数据会被跳过\n- 使用事务保证数据一致性')) {
                return;
            }

            showLoading();

            fetch('/index/excelprocessor/insertCategoriesAndSymptoms', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">✅ ' + data.msg + '</div>';

                    if (data.data) {
                        // 显示插入统计
                        html += '<h4>📊 插入统计：</h4>';
                        html += '<div class="stats-grid">';

                        html += '<div class="stat-card">';
                        html += '<div class="stat-label">分类数据</div>';
                        html += '<div style="font-size: 14px; margin-top: 10px;">';
                        html += '<div>新插入: <strong style="color: #28a745;">' + data.data.categories_inserted + '</strong></div>';
                        html += '<div>已跳过: <strong style="color: #6c757d;">' + data.data.categories_skipped + '</strong></div>';
                        html += '</div></div>';

                        html += '<div class="stat-card">';
                        html += '<div class="stat-label">症状数据</div>';
                        html += '<div style="font-size: 14px; margin-top: 10px;">';
                        html += '<div>新插入: <strong style="color: #28a745;">' + data.data.symptoms_inserted + '</strong></div>';
                        html += '<div>已跳过: <strong style="color: #6c757d;">' + data.data.symptoms_skipped + '</strong></div>';
                        html += '</div></div>';

                        if (data.data.current_stats) {
                            html += '<div class="stat-card">';
                            html += '<div class="stat-label">当前总量</div>';
                            html += '<div style="font-size: 14px; margin-top: 10px;">';
                            html += '<div>分类总数: <strong>' + data.data.current_stats.total_categories + '</strong></div>';
                            html += '<div>症状总数: <strong>' + data.data.current_stats.total_symptoms + '</strong></div>';
                            html += '</div></div>';
                        }

                        html += '<div class="stat-card"><div class="stat-value">' + data.data.data_count + '</div><div class="stat-label">Excel总行数</div></div>';
                        html += '</div>';

                        // 显示错误信息
                        if (data.data.errors && data.data.errors.length > 0) {
                            html += '<div class="alert alert-warning"><strong>⚠️ 处理过程中的警告：</strong><ul>';
                            data.data.errors.forEach(error => {
                                html += '<li>' + error + '</li>';
                            });
                            html += '</ul></div>';
                        }

                        // 成功提示
                        html += '<div class="alert alert-success">';
                        html += '<strong>✅ 分类和症状数据已成功插入数据库！</strong><br>';
                        html += '现在你可以：<br>';
                        html += '1. 点击"🔍 检查数据库状态"查看插入的数据<br>';
                        html += '2. 点击"🚀 开始处理数据（调试）"查看汤药数据是否能正确关联症状ID<br>';
                        html += '3. 确认无误后，可以继续处理汤药数据';
                        html += '</div>';
                    }

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }

        function checkDatabaseStatus() {
            showLoading();

            fetch('/index/excelprocessor/checkDatabaseStatus', {
                method: 'GET',
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">🔍 ' + data.msg + '</div>';

                    // 显示数据统计
                    if (data.data && data.data.summary) {
                        html += '<h4>📊 数据库统计：</h4>';
                        html += '<div class="stats-grid">';
                        html += '<div class="stat-card">';
                        html += '<div class="stat-value">' + data.data.summary.categories_count + '</div>';
                        html += '<div class="stat-label">分类总数</div>';
                        html += '</div>';
                        html += '<div class="stat-card">';
                        html += '<div class="stat-value">' + data.data.summary.symptoms_count + '</div>';
                        html += '<div class="stat-label">症状总数</div>';
                        html += '</div>';
                        html += '<div class="stat-card">';
                        html += '<div class="stat-value">' + data.data.summary.formulas_count + '</div>';
                        html += '<div class="stat-label">汤药总数</div>';
                        html += '</div>';
                        html += '</div>';

                        // 显示样本数据
                        if (data.data.samples) {
                            if (data.data.samples.categories && data.data.samples.categories.length > 0) {
                                html += '<h4>分类样本数据：</h4>';
                                html += '<pre>' + JSON.stringify(data.data.samples.categories, null, 2) + '</pre>';
                            }
                            if (data.data.samples.symptoms && data.data.samples.symptoms.length > 0) {
                                html += '<h4>症状样本数据：</h4>';
                                html += '<pre>' + JSON.stringify(data.data.samples.symptoms, null, 2) + '</pre>';
                            }
                            if (data.data.samples.formulas && data.data.samples.formulas.length > 0) {
                                html += '<h4>汤药样本数据：</h4>';
                                html += '<pre>' + JSON.stringify(data.data.samples.formulas, null, 2) + '</pre>';
                            }
                        }

                        // 警告信息
                        if (data.data.summary.symptoms_count === 0) {
                            html += '<div class="alert alert-warning">⚠️ 症状表为空！这会导致汤药表无法关联症状ID。请先处理症状数据。</div>';
                        }
                        if (data.data.summary.categories_count === 0) {
                            html += '<div class="alert alert-warning">⚠️ 分类表为空！这会导致症状无法关联分类ID。请先处理分类数据。</div>';
                        }
                    }

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }

        function testSplitLogic() {
            showLoading();

            fetch('/index/excelprocessor/testSplitLogic', {
                method: 'GET',
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.code === 200) {
                    let html = '<div class="alert alert-success">🧪 ' + data.msg + '</div>';

                    // 显示测试用例结果
                    if (data.test_cases) {
                        html += '<h4>📝 测试用例结果：</h4>';
                        html += '<div style="margin-bottom: 20px;">';
                        data.test_cases.forEach((test, index) => {
                            const bgColor = test.passed ? '#d4edda' : '#f8d7da';
                            const borderColor = test.passed ? '#c3e6cb' : '#f5c6cb';
                            const icon = test.passed ? '✅' : '❌';

                            html += '<div style="border: 1px solid ' + borderColor + '; margin: 10px 0; padding: 15px; border-radius: 5px; background: ' + bgColor + ';">';
                            html += '<h6>' + icon + ' 测试 ' + (index + 1) + ':</h6>';
                            html += '<div><strong>输入：</strong>"' + test.input + '"</div>';
                            html += '<div><strong>期望：</strong>' + JSON.stringify(test.expected) + '</div>';
                            html += '<div><strong>实际：</strong>' + JSON.stringify(test.actual) + '</div>';
                            html += '</div>';
                        });
                        html += '</div>';
                    }

                    // 显示Excel样本测试结果
                    if (data.excel_samples) {
                        html += '<h4>📊 Excel实际数据测试结果：</h4>';
                        html += '<div>';
                        data.excel_samples.forEach((sample) => {
                            html += '<div style="border: 1px solid #ffc107; margin: 10px 0; padding: 15px; border-radius: 5px; background: #fff8e1;">';
                            html += '<h6>第 ' + sample.row + ' 行：</h6>';

                            html += '<div style="margin: 10px 0; padding: 10px; background: #fff; border-radius: 3px;">';
                            html += '<strong>B列（主症状）：</strong>';
                            html += '<div style="margin-left: 20px;">';
                            html += '<div>原文："' + sample.B_original + '"</div>';
                            html += '<div>分割结果：' + JSON.stringify(sample.B_split) + '</div>';
                            html += '</div>';
                            html += '</div>';

                            html += '<div style="margin: 10px 0; padding: 10px; background: #fff; border-radius: 3px;">';
                            html += '<strong>C列（兼症状）：</strong>';
                            html += '<div style="margin-left: 20px;">';
                            html += '<div>原文："' + sample.C_original + '"</div>';
                            html += '<div>分割结果：' + JSON.stringify(sample.C_split) + '</div>';
                            html += '</div>';
                            html += '</div>';

                            html += '</div>';
                        });
                        html += '</div>';
                    }

                    showResult(html);
                } else {
                    showResult('<div class="alert alert-error">❌ ' + data.msg + '</div>');
                }
            })
            .catch(error => {
                hideLoading();
                showResult('<div class="alert alert-error">❌ 请求失败：' + error.message + '</div>');
            });
        }
    </script>
</body>
</html>